package com.lizi.db;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import com.mongodb.DB;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;

/**
 * Created by Administrator on 2016/9/14. MongDb 原生数据库连接 查询totalCount 用
 */
class DbUtils {

	private static MongoClient mongoClient = null;

	private final static String DATABASE = "lizidb";
	private final static String USER_NAME = "lzadmin";
	private final static String PASSWORD = "lz@2015.4.8.admin.db";
	private final static String[] servers = 
			new String[] {"221.12.127.172:53018" };

	/**
	 * 连接池大小 mongeclient 默认连接池大小 2
	 */
	private final static int POOSIZE = 2;

	private final static int TIME_OUT = 5000;

	private DbUtils() {
	}

	static {
		initMongeClient();
	}

	/**
	 * 取表连接
	 * 
	 * @param name
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public static DB getDB() {
		DB conn = mongoClient.getDB(DATABASE);
		conn.slaveOk();
		return conn;
	}

	/**
	 * 初始化
	 */
	private static void initMongeClient()  {

		List<ServerAddress> addressesList = new ArrayList<>();

		for (int i = 0; i < servers.length; i++) {
			String host = servers[i].split(":")[0];
			int port = Integer.parseInt(servers[i].split(":")[1]);
			try {
				addressesList.add(new ServerAddress(host, port));
			} catch (UnknownHostException e) {
				e.printStackTrace();
			}
		}

		List<MongoCredential> credentialList = new ArrayList<MongoCredential>();
		credentialList.add(MongoCredential.createMongoCRCredential(USER_NAME, DATABASE, PASSWORD.toCharArray()));

		MongoClientOptions options = MongoClientOptions.builder().connectionsPerHost(POOSIZE).connectTimeout(TIME_OUT)
				.build();
		mongoClient = new MongoClient(addressesList, credentialList, options);
	}

	// 不需要手动释放 mongclient 每次调用后会放回连接池 当需要释放连接时才释放
	public static void close(){
        mongoClient.close();
    }

}
